import React from "react";
import {
	Button, Form, Input, Radio, Icon, message, Switch, Spin,
	InputNumber, Select, Checkbox, DatePicker, TimePicker, Divider,
} from "antd";
import Editor from "@/utils/Editor";
import styles from "./index.less";
import {
	robotGetRobotSetting, robotSetupSaveEditInfo,
	getChannelInfoByApplicationId, postSaveChannelInfo,
} from "@/services/geographic";
import { getSetSkillGroupList, getUsersByTenantId } from "@/services/onlineSkillSet";
import Welcome from "@/pages/Account/robotSetup/welcome";
import moment from "moment";
const { Option } = Select;
let workTimeId = 0;
let sessionAssignId = 0;
let enquiryAssignId = 0;
class RobotSetup extends React.Component {
	constructor(props) {
		super(props);
		this.state = {
			welcomeType: 1,
			welcomeEditor: "",
			welcomeInput: "",
			loading: true,
			welcomeList: [],
			infoData: null,
			groupList: [],
			userList: [],
		};
	}

	componentDidMount() {
		this.getRobotSetInfo();
		this.getSkillGroupList();
		this.getUserList();
	}

	getSkillGroupList = async () => {
		const res = await getSetSkillGroupList();
		this.setState({ groupList: res });
	}

	getUserList = async () => {
		const res = await getUsersByTenantId();
		// console.log(res);
		this.setState({ userList: res });
	}

	getChannelInfo = async () => {
		const { groupList, userList } = this.state;
		const { robotId, form, applicationId } = this.props;
		const res = await getChannelInfoByApplicationId({ applicationId });
		// console.log(res);
		let channelInfo = {};
		var infoData = {
			workTime: 'full',
			keys: [],
			enquiryAssign: true,
			enquiryKeys: [],
			enquiryList: [],
			sessionAssign: true,
			sessionKeys: [],
			sessionList: [],
		};
		if(res && res.data) {
			let resData = res.data;
			if (resData.channel.sessionConfiguration == 1) {
				infoData['sessionAssign'] = true;
				resData.sessionAllotList.forEach((item, index) => {
					channelInfo[`assignGroupsA_${index}`] = item.allotType;
					channelInfo[`assignGroupA_${index}`] = item.allotType == 2 ? item.allotUserId : item.allotType == 1 ? item.allotGroupId : undefined;
					channelInfo[`isSpilloverA_${index}`] = item.overflowFlag;
					channelInfo[`queueNumA_${index}`] = item.overflowFlag == 0 ? item.queueNum : undefined;
					infoData[`assignGroupsA_${index}`] = item.allotType;
					infoData[`assignGroupA_${index}`] = item.allotType == 2 ? item.allotUserId : item.allotType == 1 ? item.allotGroupId : undefined;
					infoData[`isSpilloverA_${index}`] = item.overflowFlag;
					infoData[`queueNumA_${index}`] = item.overflowFlag == 0 ? item.queueNum : undefined;
					infoData['sessionKeys'].push({
						id: index,
						assignGroupsA: item.allotType,
						assignGroupA: item.allotUserId,
						isSpilloverA: item.overflowFlag,
					});
				})
			};
			if (resData.channel.sessionConfiguration == 2) {
				infoData['sessionAssign'] = false;
				channelInfo['consultMessage'] = resData.channel.consultMessage;
				resData.sessionConsultTypeList.forEach((i, j) => {
					channelInfo[`sessionNameA_${j}`] = i.name;
					channelInfo[`sessionRemarkA_${j}`] = i.remark;
					infoData[`sessionNameA_${j}`] = i.name;
					infoData[`sessionRemarkA_${j}`] = i.remark;
					infoData.sessionList.push({
						sessionName: i.name,
						sessionRemark: i.remark,
						sessionKeys: i.consultTypeAllotList.map((item, index) => {
							return {
								id: index,
								assignGroupsA: item.allotType,
								assignGroupA: item.allotUserId,
								isSpilloverA: item.overflowFlag,
							}
						}),
					});
					i.consultTypeAllotList.forEach((item, index) => {
						channelInfo[`assignGroupsA_${j}&${index}`] = item.allotType;
						channelInfo[`assignGroupA_${j}&${index}`] = item.allotType == 2 ? item.allotUserId : item.allotType == 1 ? item.allotGroupId : undefined;
						channelInfo[`isSpilloverA_${j}&${index}`] = item.overflowFlag;
						channelInfo[`queueNumA_${j}&${index}`] = item.overflowFlag == 0 ? item.queueNum : undefined;
						infoData[`assignGroupsA_${j}&${index}`] = item.allotType;
						infoData[`assignGroupA_${j}&${index}`] = item.allotType == 2 ? item.allotUserId : item.allotType == 1 ? item.allotGroupId : undefined;
						infoData[`isSpilloverA_${j}&${index}`] = item.overflowFlag;
						infoData[`queueNumA_${j}&${index}`] = item.overflowFlag == 0 ? item.queueNum : undefined;
						// infoData['sessionKeys'].push({
						// 	id: index,
						// 	assignGroupsA: item.allotType,
						// 	assignGroupA: item.allotUserId,
						// 	isSpilloverA: item.overflowFlag,
						// })
					})
				})
			};
			if (resData.channel.messageConfiguration == 1) {
				infoData['enquiryAssign'] = true;
				resData.leaveAllotList.forEach((item, index) => {
					channelInfo[`assignGroupsB_${index}`] = item.allotType;
					channelInfo[`assignGroupB_${index}`] = item.allotType == 2 ? item.allotUserId : item.allotType == 1 ? item.allotGroupId : undefined;
					// channelInfo[`isSpilloverB_${index}`] = item.overflowFlag;
					// channelInfo[`queueNumB_${index}`] = item.overflowFlag == 0 ? item.queueNum : undefined;
					infoData[`assignGroupsB_${index}`] = item.allotType;
					infoData[`assignGroupB_${index}`] = item.allotType == 2 ? item.allotUserId : item.allotType == 1 ? item.allotGroupId : undefined;
					// infoData[`isSpilloverB_${index}`] = item.overflowFlag;
					// infoData[`queueNumB_${index}`] = item.overflowFlag == 0 ? item.queueNum : undefined;

					// infoData[`assignGroupsB`] = item.allotType;
					// infoData[`assignGroupB`] = item.allotType == 2 ? item.allotUserId : item.allotType == 1 ? item.allotGroupId : undefined;
					infoData['enquiryKeys'].push({
						id: index,
						assignGroupsB: item.allotType,
						assignGroupB: item.allotUserId,
						// isSpilloverB: item.overflowFlag,
					})
				})
			};
			if (resData.channel.messageConfiguration == 2) {
				infoData['enquiryAssign'] = false;
				resData.leaveConsultTypeList.forEach((i, j) => {
					channelInfo[`enquiryNameB_${j}`] = i.name;
					channelInfo[`enquiryRemarkB_${j}`] = i.remark;
					infoData[`enquiryNameB_${j}`] = i.name;
					infoData[`enquiryRemarkB_${j}`] = i.remark;
					infoData.enquiryList.push({
						enquiryName: i.name,
						enquiryRemark: i.remark,
						enquiryKeys: i.consultTypeAllotList.map((item, index) => {
							return {
								id: index,
								assignGroupsB: item.allotType,
								assignGroupB: item.allotUserId,
								// isSpilloverB: item.overflowFlag,
							}
						}),
					})
					i.consultTypeAllotList.forEach((item, index) => {
						channelInfo[`assignGroupsB_${j}&${index}`] = item.allotType;
						channelInfo[`assignGroupB_${j}&${index}`] = item.allotType == 2 ? item.allotUserId : item.allotType == 1 ? item.allotGroupId : undefined;
						// channelInfo[`isSpilloverB_${j}&${index}`] = item.overflowFlag;
						// channelInfo[`queueNumB_${j}&${index}`] = item.overflowFlag == 0 ? item.queueNum : undefined;
						infoData[`assignGroupsB_${j}&${index}`] = item.allotType;
						infoData[`assignGroupB_${j}&${index}`] = item.allotType == 2 ? item.allotUserId : item.allotType == 1 ? item.allotGroupId : undefined;
						// infoData[`isSpilloverB_${j}&${index}`] = item.overflowFlag;
						// infoData[`queueNumB_${j}&${index}`] = item.overflowFlag == 0 ? item.queueNum : undefined;

						// infoData['enquiryKeys'].push({
						// 	id: index,
						// 	assignGroupsB: item.allotType,
						// 	assignGroupB: item.allotUserId,
						// })
					})
				})
			};
			if (resData.channel.userWorkTime == 1) {
				infoData['workTime'] = 'full';
			};
			if (resData.channel.userWorkTime == 2) {
				infoData['workTime'] = 'nofull';
				resData.serviceTimeList.forEach((item, index) => {
					channelInfo[`week_${index}`] = item.day;
					channelInfo[`time1_${index}`] = moment(item.serviceStartTime, 'HH:mm:ss');
					channelInfo[`time2_${index}`] = moment(item.serviceEndTime, 'HH:mm:ss');
					// infoData['keys'] = [];
					infoData['keys'].push({
						id: index,
						week: item.day,
						time1: moment(item.serviceStartTime, 'HH:mm:ss'),
						time2: moment(item.serviceEndTime, 'HH:mm:ss'),
					})
				});
			};
			if (resData.channel.overTimeFlag == 1) {
				infoData['overTimeFlag'] = true;
			} else {
				infoData['overTimeFlag'] = false;
			};
			this.setState({ infoData });
			let userInfo = form.getFieldsValue();
			form.setFieldsValue({
				...userInfo,
	
				workTime: resData.channel.userWorkTime == 1 ? 'full' : resData.channel.userWorkTime == 2 ? 'nofull' : 'full',
				onlyWork: resData.channel.onlyUserWork == 1 ? true : resData.channel.onlyUserWork == 2 ? false: undefined,
				unOnlyWork: resData.channel.onlyRobotWork == 1 ? true : resData.channel.onlyRobotWork == 2 ? false : undefined,
				overTimeFlag: resData.channel.overTimeFlag == 1 ? true : resData.channel.overTimeFlag == 2 ? false : false,
	
				overTime: resData.channel.overTimeFlag == 1 ? resData.channel.overTime : undefined,
				consultMessage: resData.channel.consultMessage,
	
				sessionAssign: resData.channel.sessionConfiguration == 1 ? true : resData.channel.sessionConfiguration == 2 ? false : true,
				enquiryAssign: resData.channel.messageConfiguration == 1 ? true : resData.channel.messageConfiguration == 2 ? false : true,
				// ticketAssign: [],
				sessionAllotList: resData.channel.sessionAllotList, // 固定会话分配
				leaveAllotList: resData.channel.leaveAllotList, // 固定留言分配
	
				...channelInfo,
			});
		} else {
			this.setState({ infoData: {
				workTime: 'full',
				keys: [],
				enquiryAssign: true,
				enquiryKeys: [
					{
						id: enquiryAssignId,
						assignGroupsB: undefined,
						assignGroupB: undefined,
						// isSpilloverB: undefined,
					},
				],
				enquiryList: [{
					enquiryName: '',
					enquiryRemark: '',
					enquiryKeys: [{
						id: enquiryAssignId,
						assignGroupsB: undefined,
						assignGroupB: undefined,
						// isSpilloverB: undefined,
					}],
				}],
				sessionAssign: true,
				sessionKeys: [
					{
						id: workTimeId,
						week: undefined,
						time1: undefined,
						time2: undefined,
					},
				],
				sessionList: [{
					sessionName: '',
					sessionRemark: '',
					sessionKeys: [{
						id: sessionAssignId,
						assignGroupsA: undefined,
						assignGroupA: undefined,
						isSpilloverA: undefined,
					}],
				}],
			} });
		}
	};

	getRobotSetInfo = () => {
		const { robotId, form } = this.props;
		let { welcomeEditor, welcomeInput } = this.state;
		let userInfo = form.getFieldsValue();
		this.setState({ loading: true }, async () => {
			const res = await robotGetRobotSetting({ id: robotId });
			let data = res;
			data.chatDisabled = res.chatDisabled === 0 ? true : false;
			form.setFieldsValue({
				...userInfo,
				name: data.name,
				nick: data.nick,
				gender: data.gender,
				description: data.description,
				welcomeType: data.welcomeType,
				unknown: data.unknown,
				chatDisabled: data.chatDisabled,
				threshold: data.threshold,
				isSimilar: data.isSimilar == 1 ? true : data.isSimilar == 2 ? false : undefined,
				voiceEnable: data.voiceEnable == 0 ? true : data.voiceEnable == 1 ? false : undefined,
			});

			let welcomeList = res.personalizedWelcome ? res.personalizedWelcome : [];
			welcomeList.unshift({
				id: "default",
				userTypeId: "default",
				welcomeType: res.welcomeType,
				welcomeContent: res.welcome,
				questionList: res.questionList ? res.questionList : [{ id: "", questionContent: "" }],
			});

			this.Welcome.initInfo(welcomeList);
			this.setState({
				loading: false,
				welcomeType: res.welcomeType,
				welcomeEditor,
				welcomeInput,
				welcomeList,
			});

			setTimeout(() => this.getChannelInfo(), 150)
		});
	};

	/**
	 * 保存
	 * @returns {*}
	 */
	save = () => {
		const { infoData } = this.state;
		const { form, robotId, applicationId } = this.props;
		const that = this;
		form.validateFields(async (errors, values) => {
			if (errors) {
				return false;
			}
			// 客服--初始化设置
			let kfData = {
				applicationId,
				userWorkTime: values.workTime == 'full' ? 1 : values.workTime == 'nofull' ? 2 : undefined,
				onlyUserWork: values.onlyWork ? 1 : 2,
				onlyRobotWork: values.unOnlyWork ? 1 : 2,
				overTimeFlag: values.overTimeFlag ? 1 : 2,
				overTime: values.overTimeFlag ? values.overTime : undefined,
				// consultMessage: '',
				sessionConfiguration: values.sessionAssign ? 1 : 2,
				messageConfiguration: values.enquiryAssign ? 1 : 2,
				sessionAllotList: values.sessionAssign ? infoData && infoData.sessionKeys.length > 0 ? infoData.sessionKeys.map((item, index) => {
					return {
						allotType: values[`assignGroupsA_${item.id}`],
						allotUserId: values[`assignGroupsA_${item.id}`] === 2 ? Number(values[`assignGroupA_${item.id}`]) : undefined,
						allotGroupId: values[`assignGroupsA_${item.id}`] === 1 ? Number(values[`assignGroupA_${item.id}`]) : undefined,
						overflowFlag: values[`isSpilloverA_${item.id}`],
						queueNum: values[`queueNumA_${item.id}`],
					}
				}) : null : null, // 固定会话分配
				leaveAllotList: values.enquiryAssign ? infoData && infoData.enquiryKeys.length > 0 ? infoData.enquiryKeys.map((item, index) => {
					return {
						allotType: values[`assignGroupsB_${item.id}`],
						allotUserId: values[`assignGroupsB_${item.id}`] === 2 ? Number(values[`assignGroupB_${item.id}`]) : undefined,
						allotGroupId: values[`assignGroupsB_${item.id}`] === 1 ? Number(values[`assignGroupB_${item.id}`]) : undefined,
						// overflowFlag: values[`isSpilloverB_${item.id}`],
						// queueNum: values[`queueNumB_${item.id}`],
					}
				}) : null : null, // 固定留言分配
				consultMessage: !values.sessionAssign ? values.consultMessage : undefined,
				sessionConsultTypeList: !values.sessionAssign && infoData && infoData.sessionList.length > 0 ? infoData.sessionList.map((item, j) => {
					return { // 按客户选择的会话咨询类型分配
						name: values[`sessionNameA_${j}`],
						remark: values[`sessionRemarkA_${j}`],
						sort: 1,
						consultTypeAllotList: item.sessionKeys.map((i, index) => {
							return {
								allotType: values[`assignGroupsA_${j}&${index}`],
								allotUserId: values[`assignGroupsA_${j}&${index}`] === 2 ? Number(values[`assignGroupA_${j}&${index}`]) : undefined,
								allotGroupId: values[`assignGroupsA_${j}&${index}`] === 1 ? Number(values[`assignGroupA_${j}&${index}`]) : undefined,
								overflowFlag: values[`isSpilloverA_${j}&${index}`],
								queueNum: values[`queueNumA_${j}&${index}`],
							}
						})
					}
				}) : null,
				leaveConsultTypeList: !values.enquiryAssign && infoData && infoData.enquiryList.length > 0 ? infoData.enquiryList.map((item, j) => {
					return { // 按客户选择的留言咨询类型分配
						name: values[`enquiryNameB_${j}`],
						remark: values[`enquiryRemarkB_${j}`],
						sort: 1,
						consultTypeAllotList: item.enquiryKeys.map((i, index) => {
							return {
								allotType: values[`assignGroupsB_${j}&${index}`],
								allotUserId: values[`assignGroupsB_${j}&${index}`] === 2 ? Number(values[`assignGroupB_${j}&${index}`]) : undefined,
								allotGroupId: values[`assignGroupsB_${j}&${index}`] === 1 ? Number(values[`assignGroupB_${j}&${index}`]) : undefined,
								// overflowFlag: values[`isSpilloverB_${j}&${index}`],
								// queueNum: values[`queueNumB_${j}&${index}`],
							}
						})
					}
				}) : null,
				serviceTimeList: infoData && infoData.keys.length > 0 ? infoData.keys.map((item, index) => {
					return {
						day: values[`week_${item.id}`],
						serviceStartTime: moment(values[`time1_${item.id}`]).format('HH:mm:ss'),
						serviceEndTime: moment(values[`time2_${item.id}`]).format('HH:mm:ss'),
					};
				}) : null,
			};
			const kfRes = await postSaveChannelInfo(kfData);
			console.log(kfRes);

			// 后台--初始化设置
			const welcomeInfo = this.Welcome.getWelcomeList();
			if (!welcomeInfo.welcome) {
				message.error({ content: "默认欢迎语不能为空" });
				return false;
			}
			const obj = {
				name: values.name,
				nick: values.nick,
				gender: values.gender,
				// description: values.description,
				unknown: values.unknown,
				chatDisabled: values.chatDisabled ? 0 : 1,
				id: robotId,
				// applicationId: robotId,
				threshold: values.threshold,
				isSimilar: values.isSimilar ? 1 : 2,
				voiceEnable: values.voiceEnable ? 0 : 1,
				description: values.name,
				nick: values.name,
				applicationId,
				gender: '男',
				...welcomeInfo,
			};

			const res = await robotSetupSaveEditInfo(obj);
			// console.log(res);
			message.info({ content: res.message });
		});
	};

	setInfoData = (value, type) => {
		const { infoData } = this.state;
		const { form } = this.props;
		let userInfo = form.getFieldsValue();
		let obj = {
			...userInfo,
			[type]: value,
			keys: type === "workTime" ? [
				{
					id: workTimeId,
					week: undefined,
					time1: undefined,
					time2: undefined,
				},
			] : infoData?.keys,
			// 固定分配;
			sessionKeys: type === "sessionAssign" && value ? [
				{
					id: sessionAssignId,
					assignGroupsA: undefined,
					assignGroupA: undefined,
					isSpilloverA: undefined,
				},
			] : infoData?.sessionKeys,
			enquiryKeys: type === "enquiryAssign" && value ? [
				{
					id: enquiryAssignId,
					assignGroupsB: undefined,
					assignGroupB: undefined,
					// isSpilloverB: undefined,
				},
			] : infoData?.enquiryKeys,
			// 自定义分配;
			sessionList: type === "sessionAssign" && !value ? [{
				sessionName: '',
				sessionRemark: '',
				sessionKeys: [{
					id: sessionAssignId,
					assignGroupsA: undefined,
					assignGroupA: undefined,
					isSpilloverA: undefined,
				}],
			}] : infoData?.sessionList,
			enquiryList: type === "enquiryAssign" && !value ? [{
				enquiryName: '',
				enquiryRemark: '',
				enquiryKeys: [{
					id: enquiryAssignId,
					assignGroupsB: undefined,
					assignGroupB: undefined,
					// isSpilloverB: undefined,
				}],
			}] : infoData?.enquiryList,
		};
		this.setState({ infoData: obj });
	};

	getInfoData = (value, type, key) => {
		let { infoData } = this.state;
		const { form } = this.props;
		let userInfo = form.getFieldsValue();
		infoData.keys.forEach((item, index) => {
			if (key === index) {
				switch (type) {
					case "week":
						item["week"] = value;
						break;
					case "time1":
						item["time1"] = value;
						break;
					case "time2":
						item["time2"] = value;
						break;
				}
			}
		});
		this.setState({ infoData });
	};

	addWorkTime = () => {
		const { infoData } = this.state;
		let keys = infoData.keys;
		let key = ++workTimeId;
		keys.push({ id: key, week: undefined, time1: undefined, time2: undefined });
		this.setState({ infoData: { ...infoData, keys } });
	};

	removeWorkTime = (k) => {
		const { infoData } = this.state;
		let keys = [];
		infoData.keys.forEach((item, index) => {
			if (k !== item.id) {
				keys.push(item);
			}
		});
		this.setState({ infoData: { ...infoData, keys } });
	};

	addSession = () => {
		const { infoData } = this.state;
		let sessionList = infoData.sessionList;
		let key = ++sessionAssignId;
		sessionList.push({
			sessionName: '',
			sessionRemark: '',
			sessionKeys: [{
				id: key,
				assignGroupsA: undefined,
				assignGroupA: undefined,
				isSpilloverA: undefined,
			}],
		});
		this.setState({ infoData: { ...infoData, sessionList } });
	};

	removeSession = (k) => {
		let { infoData } = this.state;
		infoData.sessionList = infoData.sessionList.filter((_, i) => k !== i);
		this.setState({ infoData });
	};

	addSessionItem = (sessionIndex) => {
		const { infoData } = this.state;
		let sessionList = infoData.sessionList;
		let key = ++sessionAssignId;
		sessionList[sessionIndex].sessionKeys.push({
			id: key,
			assignGroupsA: undefined,
			assignGroupA: undefined,
			isSpilloverA: undefined,
		});
		this.setState({ infoData: { ...infoData, sessionList } });
	};

	removeSessionItem = (sessionIndex, k) => {
		let { infoData } = this.state;
		infoData.sessionList[sessionIndex].sessionKeys = infoData.sessionList[sessionIndex].sessionKeys.filter((_, i) => k >= i);
		this.setState({ infoData });
	};

	addSessionAssign = () => {
		const { infoData } = this.state;
		let sessionKeys = infoData.sessionKeys;
		let key = ++sessionAssignId;
		sessionKeys.push({
			id: key,
			assignGroupsA: undefined,
			assignGroupA: undefined,
			isSpilloverA: undefined,
		});
		this.setState({ infoData: { ...infoData, sessionKeys } });
	};

	removeSessionAssign = (k) => {
		let { infoData } = this.state;
		infoData.sessionKeys = infoData.sessionKeys.filter((_, i) => k >= i);
		this.setState({ infoData });
	};

	addEnquiry = () => {
		const { infoData } = this.state;
		let enquiryList = infoData.enquiryList;
		let key = ++enquiryAssignId;
		enquiryList.push({
			enquiryName: '',
			enquiryRemark: '',
			enquiryKeys: [{
				id: key,
				assignGroupsB: undefined,
				assignGroupB: undefined,
				// isSpilloverB: undefined,
			}],
		});
		this.setState({ infoData: { ...infoData, enquiryList } });
	};

	removeEnquiry = (k) => {
		let { infoData } = this.state;
		infoData.enquiryList = infoData.enquiryList.filter((_, i) => k !== i);
		this.setState({ infoData });
	};

	addEnquiryItem = (enquiryIndex) => {
		const { infoData } = this.state;
		// console.log(infoData, enquiryIndex);
		let enquiryList = infoData.enquiryList;
		let key = ++enquiryAssignId;
		enquiryList[enquiryIndex].enquiryKeys.push({
			id: key,
			assignGroupsB: undefined,
			assignGroupB: undefined,
			// isSpilloverB: undefined,
		});
		this.setState({ infoData: { ...infoData, enquiryList } }, () => {
			// console.log(this.state.infoData);
		});
	};

	removeEnquiryItem = (enquiryIndex, k) => {
		let { infoData } = this.state;
		// console.log(infoData, enquiryIndex, k);
		infoData.enquiryList[enquiryIndex].enquiryKeys = infoData.enquiryList[enquiryIndex].enquiryKeys.filter((_, i) => k >= i);
		this.setState({ infoData });
	};

	addEnquiryAssign = () => {
		const { infoData } = this.state;
		let enquiryKeys = infoData.enquiryKeys;
		let key = ++enquiryAssignId;
		enquiryKeys.push({
			id: key,
			assignGroupsB: undefined,
			assignGroupB: undefined,
			// isSpilloverB: undefined,
		});
		this.setState({ infoData: { ...infoData, enquiryKeys } });
	};

	removeEnquiryAssign = (k) => {
		let { infoData } = this.state;
		infoData.enquiryKeys = infoData.enquiryKeys.filter((_, i) => k >= i);
		this.setState({ infoData });
	};

	render() {
		const { loading, welcomeList, infoData, groupList, userList } = this.state;
		const { getFieldDecorator, getFieldsValue } = this.props.form;
		const layout = {
			labelCol: { span: 4 },
			wrapperCol: { span: 16 },
		};
		const layoutButton = {
			wrapperCol: { span: 16, offset: 3 },
		};

		return (
			<Spin spinning={loading}>
				<Form {...layout}>
					<Form.Item label={"应用名称"}>
						{getFieldDecorator("name", {
							// rules: [{ required: true, message: "请填写应用名称" }],
						})(<Input maxLength={10} />)}
					</Form.Item>
					<Form.Item label={"客服工作时间"}>
						{getFieldDecorator("workTime", {
							initialValue: 'full',
							// rules: [{ required: true, message: "请选择客服工作时间" }],
						})(
							<Radio.Group onChange={(e) => this.setInfoData(e.target.value, "workTime")}>
								<Radio value='full'>全天（有人工客服在线即可转人工）</Radio>
								<Radio value='nofull'>非全天</Radio>
							</Radio.Group>
						)}
						{infoData && infoData.workTime === "full" ? (
							<div>
								{getFieldDecorator("onlyWork", { valuePropName: "checked" })(
									<Checkbox>工作时间内仅人工客服接待</Checkbox>
								)}
							</div>
						) : null}
						{infoData && infoData.workTime === "nofull" ? (
							<div style={{ padding: 20, background: "#FAFAFA", borderRadius: "4px", }}>
								{infoData && infoData.keys.length > 0 ? infoData.keys.map((item, index) => {
									return (
										<div key={index}>
											{getFieldDecorator(`week_${item.id}`, {
												initialValue: item.week,
												rules: [{ required: true, message: "请选择" }],
											})(
												<Select style={{ width: "190px" }} placeholder='请选择' onChange={(e) => this.getInfoData(e, "week", item.id)}>
													<Option value='1'>周一</Option>
													<Option value='2'>周二</Option>
													<Option value='3'>周三</Option>
													<Option value='4'>周四</Option>
													<Option value='5'>周五</Option>
													<Option value='6'>周六</Option>
													<Option value='7'>周日</Option>
												</Select>
											)}
											{getFieldDecorator(`time1_${item.id}`, { initialValue: item.time1 })(
												<TimePicker
													format="HH:mm:ss"
													style={{ width: "190px", marginLeft: 10 }}
													onChange={(e) => this.getInfoData(e, "time1", item.id)}
												/>
											)}
											{getFieldDecorator(`time2_${item.id}`, { initialValue: item.time2 })(
												<TimePicker
													format="HH:mm:ss"
													style={{ width: "190px", marginLeft: 10 }}
													onChange={(e) => this.getInfoData(e, "time2", item.id)}
												/>
											)}
											{(index + 1) === infoData.keys.length ? (
												<Button type='link' onClick={this.addWorkTime}>
													<Icon
														type='plus-circle'
														theme='filled'
														style={{ fontSize: "18px", verticalAlign: "-4px", }}
													/>
													<span>添加工作时间</span>
												</Button>
											) : (
												<Button type='link' onClick={() => this.removeWorkTime(item.id)}>
													<Icon
														type='minus-circle'
														theme='filled'
														style={{
															fontSize: "18px",
															verticalAlign: "-4px",
														}}
													/>
												</Button>
											)}
										</div>
									);
								}) : null}
								<div style={{ margin: "20px 0", lineHeight: "20px" }}>
									{getFieldDecorator("onlyWork", { valuePropName: "checked" })(
										<Checkbox>工作时间内仅人工客服接待</Checkbox>
									)}
								</div>
								<div style={{ lineHeight: "20px" }}>
									{getFieldDecorator("unOnlyWork", { valuePropName: "checked" })(
										<Checkbox>非工作时间仅机器人接待</Checkbox>
									)}
								</div>
							</div>
						) : null}
					</Form.Item>
					<Form.Item label={"机器人延迟回复"}>
						{getFieldDecorator("overTimeFlag")(
							<Radio.Group onChange={(e) => this.setInfoData(e.target.value, "overTimeFlag")}>
								<Radio value={true}>开启</Radio>
								<Radio value={false}>关闭</Radio>
							</Radio.Group>
						)}
						{infoData && infoData.overTimeFlag ? (
							<span>
								<span>延时&nbsp;&nbsp;</span>
								{getFieldDecorator("overTime", {
									initialValue: 1,
									rules: [{ required: true, message: "请填写延时时长" }],
								})(<InputNumber min={1} />)}
								<span>&nbsp;&nbsp;秒</span>
							</span>
						) : null}
					</Form.Item>
					<Divider />
					<Form.Item label='会话分配'>
						{getFieldDecorator("sessionAssign", { initialValue: true })(
							<Radio.Group onChange={(e) => this.setInfoData(e.target.value, "sessionAssign")}>
								<Radio value={true}>固定分配</Radio>
								<Radio value={false}>按客户选择的咨询类型分配</Radio>
							</Radio.Group>
						)}
						{infoData && infoData.sessionAssign ? (
							<div>
								{infoData && infoData.sessionKeys.length > 0 ? infoData.sessionKeys.map((item, index) => {
									return <>
										{getFieldDecorator(`assignGroupsA_${index}`, { initialValue: 1 })(
											<Select style={{ width: "190px" }} onChange={(e) => this.setInfoData(e, `assignGroupsA_${index}`)}>
												<Option value={1}>分配给技能组</Option>
												<Option value={2}>分配给客服</Option>
											</Select>
										)}
										{getFieldDecorator(`assignGroupA_${index}`)(
											<Select style={{ width: "190px", marginLeft: 10 }}>
												{infoData[`assignGroupsA_${index}`] === 1 ? (
													groupList.map((item, index) => {
														return <Option value={item.groupId} key={index}>{item.groupName}</Option>
													})
												) : infoData[`assignGroupsA_${index}`] === 2 ? (
													userList.map((item, index) => {
														return <Option value={item.userId} key={index}>{item.nick}</Option>
													})
												): (
													groupList.map((item, index) => {
														return <Option value={item.groupId} key={index}>{item.groupName}</Option>
													})
												)}
											</Select>
										)}
										{getFieldDecorator(`isSpilloverA_${index}`, { initialValue: 1 })(
											<Select style={{ width: "190px", marginLeft: 10 }}  onChange={(e) => {
												if (e === 0) {
													this.addSessionAssign()
												} else {
													this.removeSessionAssign(item.id)
												};
												this.setInfoData(e, `isSpilloverA_${index}`);
											}}>
												<Option value={1}>不溢出</Option>
												<Option value={0}>溢出</Option>
											</Select>
										)}
										{infoData[`isSpilloverA_${index}`] === 0 ? (
											<>
												<span> 排队人数大于 </span>
												{getFieldDecorator(`queueNumA_${index}`, {
													initialValue: 0
												})(<InputNumber min={0} style={{ width: '60px' }} />)}
												<span> 时</span>
											</>
										) : null}
									</>
								}) : null}
							</div>
						) : (
							<>
								<div style={{ display: "flex" }}>
									<span style={{ marginRight: 10 }}>咨询引导语</span>
									<div style={{ width: "calc(100% - 80px)" }}>
										{getFieldDecorator("consultMessage")(
											<Input placeholder='请输入咨询引导语' />
										)}
										<p style={{ lineHeight: "16px", color: "#13c2f3" }}>
											用户申请接入人工客服前会显示此提示
										</p>
									</div>
								</div>
								{infoData && infoData.sessionList.length > 0 ? infoData.sessionList.map((sessionItem, sessionIndex) => {
									return <>
										<div style={{ padding: 20, background: "#FAFAFA", borderRadius: "4px", }}>
											<div style={{ marginBottom: 16 }}>
												{getFieldDecorator(`sessionNameA_${sessionIndex}`)(<Input placeholder='请输入咨询类型名称' />)}
											</div>
											<div style={{ marginBottom: 16 }}>
												{getFieldDecorator(`sessionRemarkA_${sessionIndex}`)(<Input.TextArea placeholder='请输入咨询类型描述' />)}
											</div>
											{sessionItem && sessionItem.sessionKeys.length > 0 ? sessionItem.sessionKeys.map((item, index) => {
												return (
													<>
														<div style={{ display: "inline-block" }} key={index}>
															{getFieldDecorator(`assignGroupsA_${sessionIndex}&${index}`, { initialValue: 1 })(
																<Select style={{ width: "190px" }} onChange={(e) => this.setInfoData(e, `assignGroupsA_${sessionIndex}&${item.id}`)}>
																	<Option value={1}>分配给技能组</Option>
																	<Option value={2}>分配给客服</Option>
																</Select>
															)}
															{getFieldDecorator(`assignGroupA_${sessionIndex}&${index}`)(
																<Select style={{ width: "190px", marginLeft: 10 }}>
																	{infoData[`assignGroupsA_${sessionIndex}&${index}`] === 1 ? (
																		groupList.map((item, index) => {
																			return <Option value={item.groupId} key={index}>{item.groupName}</Option>
																		})
																	) : infoData[`assignGroupsA_${sessionIndex}&${index}`] === 2 ? (
																		userList.map((item, index) => {
																			return <Option value={item.userId} key={index}>{item.nick}</Option>
																		})
																	): (
																		groupList.map((item, index) => {
																			return <Option value={item.groupId} key={index}>{item.groupName}</Option>
																		})
																	)}
																</Select>
															)}
															{getFieldDecorator(`isSpilloverA_${sessionIndex}&${index}`, { initialValue: 1 })(
																<Select style={{ width: "190px", marginLeft: 10 }} onChange={(e) => {
																	if (e === 0) {
																		this.addSessionItem(sessionIndex)
																	} else {
																		this.removeSessionItem(sessionIndex, index)
																	};
																	this.setInfoData(e, `isSpilloverA_${sessionIndex}&${index}`)
																}}>
																	<Option value={1}>不溢出</Option>
																	<Option value={0}>溢出</Option>
																</Select>
															)}
															{infoData[`isSpilloverA_${sessionIndex}&${index}`] === 0 ? (
																<>
																	<span> 排队人数大于 </span>
																	{getFieldDecorator(`queueNumA_${sessionIndex}&${index}`, {
																		initialValue: 0
																	})(<InputNumber min={0} style={{ width: '60px' }} />)}
																	<span> 时</span>
																</>
															) : null}
														</div>
													</>
												);
											}) : null}
										</div>
										{(sessionIndex + 1) === infoData.sessionList.length ? (
											<Button type='link' onClick={this.addSession}>
												<Icon type='plus-circle' theme='filled' style={{ fontSize: "18px", verticalAlign: "-4px", }} />
											</Button>
										) : (
											<Button type='link' onClick={() => this.removeSession(sessionIndex)}>
												<Icon type='minus-circle' theme='filled' style={{ fontSize: "18px", verticalAlign: "-4px", }} />
											</Button>
										)}
									</>
								}) : null}
							</>
						)}
					</Form.Item>
					<Divider />
					<Form.Item label='留言分配'>
						{getFieldDecorator("enquiryAssign", { initialValue: true })(
							<Radio.Group onChange={(e) => this.setInfoData(e.target.value, "enquiryAssign")}>
								<Radio value={true}>固定分配</Radio>
								<Radio value={false}>按客户选择的咨询类型分配</Radio>
							</Radio.Group>
						)}
						{infoData && infoData.enquiryAssign ? (
							<div>
								{infoData && infoData.enquiryKeys.length > 0 ? infoData.enquiryKeys.map((item, index) => {
									return (
										<>
											{getFieldDecorator(`assignGroupsB_${index}`, { initialValue: 1 })(
												<Select style={{ width: "190px" }} onChange={(e) => this.setInfoData(e, `assignGroupsB_${index}`)}>
													<Option value={1}>分配给技能组</Option>
													<Option value={2}>分配给客服</Option>
												</Select>
											)}
											{getFieldDecorator(`assignGroupB_${index}`)(
												<Select style={{ width: "190px", marginLeft: 10 }}>
													{infoData[`assignGroupsB_${index}`] === 1 ? (
														groupList.map((item, index) => {
															return <Option value={item.groupId} key={index}>{item.groupName}</Option>
														})
													) : infoData[`assignGroupsB_${index}`] === 2 ? (
														userList.map((item, index) => {
															return <Option value={item.userId} key={index}>{item.nick}</Option>
														})
													): (
														groupList.map((item, index) => {
															return <Option value={item.groupId} key={index}>{item.groupName}</Option>
														})
													)}
												</Select>
											)}
											{/* {getFieldDecorator(`isSpilloverB_${index}`, { initialValue: 1 })(
												<Select style={{ width: "190px", marginLeft: 10 }} onChange={(e) => {
													if (e === 0) {
														this.addEnquiryAssign()
													} else {
														this.removeEnquiryAssign(item.id)
													};
													this.setInfoData(e, `isSpilloverB_${index}`);
												}}>
													<Option value={1}>不溢出</Option>
													<Option value={0}>溢出</Option>
												</Select>
											)} */}
											{/* {infoData[`isSpilloverB_${index}`] === 0 ? (
												<>
													<span> 排队人数大于 </span>
													{getFieldDecorator(`queueNumB_${index}`, {
														initialValue: 0
													})(<InputNumber min={0} style={{ width: '60px' }} />)}
													<span> 时</span>
												</>
											) : null} */}
										</>
									)
								}) : null}
							</div>
						) : (
							<>
								{infoData && infoData.enquiryList.length > 0 ? infoData.enquiryList.map((enquiryItem, j) => {
									return <>
										<div style={{ padding: 20, background: "#FAFAFA", borderRadius: "4px", }}>
											{/* <div style={{ display: "flex" }}>
												<span style={{ marginRight: 10 }}>咨询引导语</span>
												<div style={{ width: "calc(100% - 80px)" }}>
													<Input placeholder='请输入咨询引导语' />
													<p style={{ lineHeight: "16px", color: "#13c2f3" }}>用户申请接入人工客服前会显示此提示</p>
												</div>
											</div> */}
											<div style={{ marginBottom: 16 }}>
												{getFieldDecorator(`enquiryNameB_${j}`)(<Input placeholder='请输入咨询类型名称' />)}
											</div>
											<div style={{ marginBottom: 16 }}>
												{getFieldDecorator(`enquiryRemarkB_${j}`)(<Input.TextArea placeholder='请输入咨询类型描述' />)}
											</div>
											{enquiryItem && enquiryItem.enquiryKeys.length > 0 ? enquiryItem.enquiryKeys.map((item, index) => {
												return (
													<>
														<div style={{ display: "inline-block" }} key={index}>
															{getFieldDecorator(`assignGroupsB_${j}&${index}`, { initialValue: 1 })(
																<Select style={{ width: "190px" }} onChange={(e) => this.setInfoData(e, `assignGroupsB_${j}&${index}`)}>
																	<Option value={1}>分配给技能组</Option>
																	<Option value={2}>分配给客服</Option>
																</Select>
															)}
															{getFieldDecorator(`assignGroupB_${j}&${index}`)(
																<Select style={{ width: "190px", marginLeft: 10 }}>
																	{infoData[`assignGroupsB_${j}&${index}`] == 1 ? (
																		groupList.map((item, index) => {
																			return <Option value={item.groupId} key={index}>{item.groupName}</Option>
																		})
																	) : infoData[`assignGroupsB_${j}&${index}`] == 2 ? (
																		userList.map((item, index) => {
																			return <Option value={item.userId} key={index}>{item.nick}</Option>
																		})
																	): (
																		groupList.map((item, index) => {
																			return <Option value={item.groupId} key={index}>{item.groupName}</Option>
																		})
																	)}
																</Select>
															)}
															{/* {getFieldDecorator(`isSpilloverB_${j}&${index}`, { initialValue: 1 })(
																<Select style={{ width: "190px", marginLeft: 10 }} onChange={(e) => {
																	if (e === 0) {
																		this.addEnquiryItem(j)
																	} else {
																		this.removeEnquiryItem(j, index)
																	};
																	this.setInfoData(e, `isSpilloverB_${j}&${index}`);
																}}>
																	<Option value={1}>不溢出</Option>
																	<Option value={0}>溢出</Option>
																</Select>
															)} */}
															{/* {infoData[`isSpilloverB_${j}&${index}`] === 0 ? (
																<>
																	<span> 排队人数大于 </span>
																	{getFieldDecorator(`queueNumB_${j}&${index}`, {
																		initialValue: 0
																	})(<InputNumber min={0} style={{ width: '60px' }} />)}
																	<span> 时</span>
																</>
															) : null} */}
														</div>
													</>
												);
											}) : null}
										</div>
										{(j + 1) === infoData.enquiryList.length ? (
											<Button type='link' onClick={this.addEnquiry}>
												<Icon type='plus-circle' theme='filled' style={{ fontSize: "18px", verticalAlign: "-4px", }} />
											</Button>
										) : (
											<Button type='link' onClick={() => this.removeEnquiry(j)}>
												<Icon type='minus-circle' theme='filled' style={{ fontSize: "18px", verticalAlign: "-4px", }} />
											</Button>
										)}
									</>
								}) : null}
							</>
						)}
					</Form.Item>
					<Divider />
					{/* <Form.Item label='工单分配'>
						{getFieldDecorator("ticketAssign", { valuePropName: "checked" })(
							<Checkbox.Group style={{ width: "100%" }}>
								<Checkbox value='A'>工单技能组A</Checkbox>
								<Checkbox value='B'>工单技能组B</Checkbox>
							</Checkbox.Group>
						)}
					</Form.Item> */}
					{/* <Form.Item label={"昵称"}>
						{getFieldDecorator("nick", {
							rules: [{ required: true, message: "请填写机器人昵称" }],
						})(<Input maxLength={10} />)}
					</Form.Item> */}
					{/* <Form.Item label={"性别"}>
						{getFieldDecorator("gender", {
							rules: [{ required: true, message: "请填写机器人性别" }],
						})(<Input maxLength={200} />)}
					</Form.Item> */}
					{/* <Form.Item label={"介绍"}>
						{getFieldDecorator("description", {
							rules: [{ required: true, message: "请填写机器人介绍" }],
						})(<Input maxLength={200} />)}
					</Form.Item> */}
					<Form.Item label={"欢迎语"} className={styles.welcome}>
						<Welcome
							welcomeList={welcomeList}
							onRef={(ref) => (this.Welcome = ref)}
						/>
					</Form.Item>
					<Form.Item label={"未知问题回答"}>
						{getFieldDecorator("unknown", {
							// rules: [{ required: true, message: "请填写未知问题回答" }],
						})(<Input maxLength={200} />)}
					</Form.Item>
					<Form.Item label={"闲聊知识库"}>
						{getFieldDecorator("chatDisabled", { valuePropName: "checked" })(
							<Switch />
						)}
					</Form.Item>
					<Form.Item label={"输入联想"}>
						{getFieldDecorator("isSimilar", { valuePropName: "checked" })(
							<Switch />
						)}
					</Form.Item>
					{this.props.channel == "12" ? (
						<Form.Item label={"语音输入"}>
							{getFieldDecorator("voiceEnable", { valuePropName: "checked" })(
								<Switch />
							)}
						</Form.Item>
					) : null}
					{window.isShowThreshold ? (
						<Form.Item label={"知识库阈值"}>
							{getFieldDecorator("threshold", { initialValue: 0.7 })(
								<InputNumber max='1' min='0' />
							)}
						</Form.Item>
					) : ("")}

					<Form.Item {...layoutButton}>
						<Button type={"primary"} onClick={this.save}>保存</Button>
					</Form.Item>
				</Form>
			</Spin>
		);
	}
}

export default Form.create()(RobotSetup);
